package cn.alm.springaialibaba.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

@RestController
@RequestMapping("audio")
public class AudioModelController {

    @Autowired
    private DashScopeSpeechSynthesisModel audioModel;

    private static final String FILE_PATH = "D:/dev/";

    @GetMapping("tts")
    public void tts(@RequestParam String text) throws IOException {
        DashScopeSpeechSynthesisOptions options = DashScopeSpeechSynthesisOptions.builder()
                //  语速
                .withSpeed(1.0)
                //  语调
                .withPitch(1.0)
                //  音量
                .withVolume(60)
                .build();
        SpeechSynthesisPrompt prompt = new SpeechSynthesisPrompt(text, options);
        SpeechSynthesisResponse call = audioModel.call(prompt);
        File file = new File(FILE_PATH + "output.mp3");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            ByteBuffer buffer = call.getResult().getOutput().getAudio();
            while (buffer.hasRemaining()) {
                fos.write(buffer.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException(e.getMessage());
        }
    }
}
